package com_.dxy_test_.try_catch_;

/**
 * @Description 测试try catch finally的过程
 *
 * 两种情况：
 *
 * 一、finally无返回：那么try或者catch中的返回值会暂存，即使finally中改变这个值，最终也是返回暂存值
 *
 * 二、finally有返回，那么暂存失效，会直接返回finally中计算后的值，所以不要在finally中写返回
 *
 * @Author dangxianyue
 * @Date 2023/12/29 15:24
 */
public class TryCatchTest {

    // 返回1
    public static int getValue0() {
        int result = 0;
        try {
            result = 1;
            return result;
        } catch (ArithmeticException e) {
            System.out.println("Caught an exception");
            result = 1;
            return result;
        } finally {
            result += 5; // 在finally块中修改返回值
            System.out.println("Finally block executed");
        }
    }


    // 返回2
    public static int getValue1() {
        int result = 0;
        try {
            result = 10 / 0; // 这里会抛出一个异常
            return result;
        } catch (ArithmeticException e) {
            System.out.println("Caught an exception");
            result = 2;
            return result;
        } finally {
            result += 5; // 在finally块中修改返回值
            System.out.println("Finally block executed");
        }
    }

    // 返回7
    public static int getValue2() {
        int result = 0;
        try {
            result = 10 / 0; // 这里会抛出一个异常
            return result;
        } catch (ArithmeticException e) {
            System.out.println("Caught an exception");
            result = 2;
            return result;
        } finally {
            result += 5; // 在finally块中修改返回值
            System.out.println("Finally block executed");
            return result;
        }
    }

    public static void main(String[] args) {
        // int result = getValue0();
        // int result = getValue1();
        int result = getValue2();
        System.out.println("Result: " + result);
    }
}
